package com.mxpio.erp.plm.controller;

import com.mxpio.erp.common.plm.entity.*;
import com.mxpio.erp.common.plm.service.*;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.service.DeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "ProjectReportController", description = "统计报表")
@RestController
@RequestMapping("/erp/plm/pro/report/")
public class ProjectReportController {

    @Autowired
    private ProjectReportService projectReportService;
    @Autowired
    private VEProjectTypeService veProjectTypeService;
    @Autowired
    private VEProjectOverdueService veProjectOverdueService;
    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired
    private VEProjectDangerNumService veProjectDangerNumService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private ProjectDangerService projectDangerService;


    @GetMapping("sort/count/{infoDeptId}")
    @Operation(summary = "获取各个状态的统计", description = "获取各个状态的统计", method = "GET")
    public Result<List<ProjectReport>> getCount(@PathVariable(name = "infoDeptId", required = true) String infoDeptId)  {
        List<ProjectReport> projectReport =projectReportService.getCount(infoDeptId);
        return Result.OK(projectReport);
    }

    @GetMapping("sort/count/type/{infoDeptId}")
    @Operation(summary = "获取各个类型项目的--状态统计", description = "获取各个类型项目的--状态统计", method = "GET")
    public Result<List<ProjectReport>> getTypeCount(@PathVariable(name = "infoDeptId", required = true) String infoDeptId)  {
        List<ProjectReport> projectReport =projectReportService.getTypeCount(infoDeptId);
        return Result.OK(projectReport);
    }

    @GetMapping("sort/count/complete/{infoDeptId}")
    @Operation(summary = "获取项目的完成是否的数量统计", description = "获取项目的完成是否的数量统计", method = "GET")
    public Result<ProjectReport> getCompleteCount(@PathVariable(name = "infoDeptId", required = true) String infoDeptId)  {
        ProjectReport projectReport =projectReportService.getCompleteCount(infoDeptId);
        return Result.OK(projectReport);
    }

    @GetMapping("proType//list")
    @Operation(summary = "项目类型分布", description = "项目类型分布", method = "GET")
    public Result<List<VEProjectType>> typeList(Criteria criteria) throws UnsupportedEncodingException {
        List<VEProjectType> list = veProjectTypeService.list(criteria);
        return Result.OK(list);
    }

//    @GetMapping("inspection/day/page")
//    @Operation(summary = "当日完成检验-分页 ", description = "当日完成检验-分页 ", method = "GET")
//    public Result<Page<VEInspectionBillCompleteInspectionDay>> dayPage(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
//        Pageable pageAble = PageRequest.of(pageNo-1, pageSize);
//        Page<VEInspectionBillCompleteInspectionDay> page = veInspectionBillCompleteInspectionDayService.listPage(pageAble, criteria);
//        return Result.OK(page);
//    }

    @GetMapping("complete/list/{infoDeptId}")
    @Operation(summary = "个人任务完成数量最大的TOP10", description = "个人任务完成数量最大的TOP10", method = "GET")
    public Result<List<ProjectReport>> taskCompleteNum(@PathVariable(name = "infoDeptId", required = true) String infoDeptId) throws UnsupportedEncodingException {
        List<ProjectReport> projectReports = projectReportService.getTaskCompleteNum(infoDeptId);
        List<ProjectReport> top10 = projectReports.stream()
                .sorted(Comparator.comparingLong(ProjectReport::getTaskNum).reversed())
                .limit(10)
                .collect(Collectors.toList());

        List<ProjectReport> projectReports1 = new ArrayList<>();
        for (ProjectReport projectReport : top10) {
            if (projectReport.getTaskNum() > 0){
                projectReports1.add(projectReport);
            }
        }

        return Result.OK(projectReports1);
    }

    @GetMapping("overdue/list")
    @Operation(summary = "项目逾期时长分布", description = "项目逾期时长分布", method = "GET")
    public Result<List<VEProjectOverdue>> overdueList(Criteria criteria) throws UnsupportedEncodingException {
        List<VEProjectOverdue> list = veProjectOverdueService.getlist(criteria);
        return Result.OK(list);
    }

    @GetMapping("overdueDay/list")
    @Operation(summary = "逾期项目天数最大的TOP5", description = "逾期项目天数最大的TOP5", method = "GET")
    public Result<List<ProjectInfo>> dayList(Criteria criteria) throws UnsupportedEncodingException {
        List<Object> criterions = criteria.getCriterions();
        List<String> codes = new ArrayList<>();
        if (!criterions.isEmpty()){
            Iterator<Object> iterator = criterions.iterator();
            while(iterator.hasNext()){
                Object next = iterator.next();
                if (next instanceof SimpleCriterion){
                    SimpleCriterion simpleCriterion = (SimpleCriterion)next;
                    if (StringUtils.equals(simpleCriterion.getFieldName(),"infoDeptId")){
                        String value = (String) simpleCriterion.getValue();
                        //查询部门以及子部门
//                        Dept dept = JpaUtil.linq(Dept.class).equal("deptCode", value).findOne();
                        List<Dept> deptCode = deptService.list(Dept.class, Criteria.create().addCriterion("deptCode", Operator.EQ, value));
                        Dept dept = deptCode.get(0);
                        List<String> deptCodes    =  projectInfoService.getchildren(dept);
                        codes.add(value);
                        codes.addAll(deptCodes);
                    }
                }
            }
        }
        Criteria c = Criteria.create();
        c.addCriterion("infoDeptId", Operator.IN,codes);////对应的部门子级

        List<ProjectInfo> list = projectInfoService.list(ProjectInfo.class,c);

        List<ProjectInfo> topFiveOverdue = list.stream()
                .sorted(Comparator.comparingLong(ProjectInfo::getOverdueDay).reversed())
                .limit(5)
                .collect(Collectors.toList());
//        List<ProjectInfo> topFiveLeastOverdue = list.stream()
//                .sorted(Comparator.comparingLong(ProjectInfo::getOverdueDay)) // 按 overdueDay 升序排序
//                .limit(5) // 限制结果大小为5
//                .collect(Collectors.toList()); // 收集结果到新的列表中
        List<ProjectInfo> projectInfos = new ArrayList<>();
        //当为0的时候不传
        for (ProjectInfo projectInfo : topFiveOverdue){
            if (projectInfo.getOverdueDay() != 0)
                projectInfos.add(projectInfo);
        }
        return Result.OK(projectInfos);
    }

    @GetMapping("danger/list")
    @Operation(summary = "项目风险数量TOP5", description = "项目风险数量TOP5", method = "GET")
    public Result<List<VEProjectDangerNum>> List(Criteria criteria) throws UnsupportedEncodingException {
        List<Object> criterions = criteria.getCriterions();
        List<String> codes = new ArrayList<>();
        if (!criterions.isEmpty()){
            Iterator<Object> iterator = criterions.iterator();
            while(iterator.hasNext()){
                Object next = iterator.next();
                if (next instanceof SimpleCriterion){
                    SimpleCriterion simpleCriterion = (SimpleCriterion)next;
                    if (StringUtils.equals(simpleCriterion.getFieldName(),"infoDeptId")){
                        String value = (String) simpleCriterion.getValue();
                        //查询部门以及子部门
//                        Dept dept = JpaUtil.linq(Dept.class).equal("deptCode", value).findOne();
                        List<Dept> deptCode = deptService.list(Dept.class, Criteria.create().addCriterion("deptCode", Operator.EQ, value));
                        Dept dept = deptCode.get(0);
                        List<String> deptCodes    =  projectInfoService.getchildren(dept);
                        codes.add(value);
                        codes.addAll(deptCodes);
                    }
                }
            }
        }
        Criteria c = Criteria.create();
        c.addCriterion("infoDeptId", Operator.IN,codes);////对应的部门子级


        List<VEProjectDangerNum> list = veProjectDangerNumService.list(c);
        for (VEProjectDangerNum veProjectDangerNum : list){
            veProjectDangerNum.setTotalNum(veProjectDangerNum.getGNum() + veProjectDangerNum.getZNum() + veProjectDangerNum.getDNum());
        }
        List<VEProjectDangerNum> topFiveOverdue = list.stream()
                .sorted(Comparator.comparingLong(VEProjectDangerNum::getTotalNum).reversed())
                .limit(5)
                .collect(Collectors.toList());
        return Result.OK(topFiveOverdue);
    }

    @GetMapping("sort/overdue/info/{infoDeptId}")
    @Operation(summary = "获取逾期项目", description = "获取逾期项目", method = "GET")
    public Result<Page<ProjectInfo>> getOverdueInfo(@PathVariable(name = "infoDeptId", required = true) String infoDeptId,
                                                    @Parameter(description="每页条数")Integer pageSize,
                                                    @Parameter(description="页号")Integer pageNo)  {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<ProjectInfo> projectReport =projectReportService.getOverdueInfo(page,infoDeptId);
        return Result.OK(projectReport);
    }

    @GetMapping("info/page")
    @Operation(summary = "项目列表", description = "项目列表（分页）", method = "GET")
    public Result<Page<ProjectInfo>> infoPage(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
//        projectInfoService.calculateProgress();//计算进度

        List<Object> criterions = criteria.getCriterions();
        List<String> codes = new ArrayList<>();
        if (!criterions.isEmpty()){
            Iterator<Object> iterator = criterions.iterator();
            while(iterator.hasNext()){
                Object next = iterator.next();
                if (next instanceof SimpleCriterion){
                    SimpleCriterion simpleCriterion = (SimpleCriterion)next;
                    if (StringUtils.equals(simpleCriterion.getFieldName(),"infoDeptId")){
                        String value = (String) simpleCriterion.getValue();
                        //查询部门以及子部门
//                        Dept dept = JpaUtil.linq(Dept.class).equal("deptCode", value).findOne();
                        List<Dept> deptCode = deptService.list(Dept.class, Criteria.create().addCriterion("deptCode", Operator.EQ, value));
                        Dept dept = deptCode.get(0);
                        List<String> deptCodes    =  projectInfoService.getchildren(dept);
                        codes.add(value);
                        codes.addAll(deptCodes);
                    }
                }
            }
        }

        Criteria c = Criteria.create();
        c.addCriterion("infoDeptId", Operator.IN,codes);////对应的部门子级

        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<ProjectInfo> pageResult = projectInfoService.listPage( page, c);
        return Result.OK(pageResult);
    }


    @GetMapping("danger/page")
    @Operation(summary = "项目风险列表", description = "项目风险列表（分页）", method = "GET")
    public Result<Page<ProjectDanger>> dangerPage(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        List<Object> criterions = criteria.getCriterions();
        List<String> codes = new ArrayList<>();
        if (!criterions.isEmpty()){
            Iterator<Object> iterator = criterions.iterator();
            while(iterator.hasNext()){
                Object next = iterator.next();
                if (next instanceof SimpleCriterion){
                    SimpleCriterion simpleCriterion = (SimpleCriterion)next;
                    if (StringUtils.equals(simpleCriterion.getFieldName(),"infoDeptId")){
                        String value = (String) simpleCriterion.getValue();
                        //查询部门以及子部门
//                        Dept dept = JpaUtil.linq(Dept.class).equal("deptCode", value).findOne();
                        List<Dept> deptCode = deptService.list(Dept.class, Criteria.create().addCriterion("deptCode", Operator.EQ, value));
                        Dept dept = deptCode.get(0);
                        List<String> deptCodes    =  projectInfoService.getchildren(dept);
                        codes.add(value);
                        codes.addAll(deptCodes);
                    }
                }
            }
        }

        Criteria c = Criteria.create();
        c.addCriterion("infoDeptId", Operator.IN,codes);////对应的部门子级
        Page<ProjectDanger> pageResult = projectDangerService.listPage(ProjectDanger.class, page, c);
        return Result.OK(pageResult);
    }
}
